package com.security.service;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Telephony;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.security.broadcast.SimStateReceiver;
import com.security.location.GPSUtil;
import com.security.sms.OnSmsInboxListener;
import com.security.sms.SMS;
import com.security.sms.SMSBean;
import com.security.sms.SmsInboxUtils;
import java.util.List;
public class SecurityService extends Service {
    ContentResolver contentResolver;
    SmsObserver smsObserver;
    private SharedPreferences sp;
    private DevicePolicyManager dpm;
    private SimStateReceiver simStateReceiver;
    private boolean hasRegister = false;
    private GPSUtil gpsUtil;
    private long futhertime=0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent){return null;}
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onCreate() {
        super.onCreate();
        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        sp = getSharedPreferences("data", Context.MODE_PRIVATE);
        contentResolver = getContentResolver();
        smsObserver = new SmsObserver(new Handler());
        contentResolver.registerContentObserver(Telephony.MmsSms.CONTENT_URI, true, smsObserver);
        registerSimReceiver(true);
        gpsUtil=new GPSUtil(getApplicationContext());
    }
    class SmsObserver extends ContentObserver {
        public SmsObserver(Handler handler) {
            super(handler);
        }
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            SmsInboxUtils smsInboxUtils = new SmsInboxUtils();
            new Handler().postDelayed(() -> {//收到短信后2秒内写入数据库才能读取
                smsInboxUtils.getSms(SecurityService.this, new OnSmsInboxListener() {
                    @Override
                    public void onSuccess(List list) {
                        delayExe(list);
                    }
                    @Override
                    public void onFailed(){}
                });
            }, 3000);

        }
    }
    public void delayExe(List list){
        Log.i("emm","执行一次");
        if (SystemClock.elapsedRealtime()>futhertime){
            for (Object o : list) {
                SMSBean b = (SMSBean) o;
                String mobile = sp.getString("securityMobile", "NULL");
                Log.i("emmm手机",b.getNumber()+"   "+mobile);
                if (b.getNumber().equals(mobile)) {//是安全手机发来的指令耶
                    SharedPreferences.Editor editor = sp.edit();
                    switch (b.body) {
                        case "锁定手机":
                            if (sp.getBoolean("lockMobile", true)) { dpm.lockNow(); }
                            break;
                        case "开启SIM检测":
                            editor.putBoolean("detectSIM", true);
                            editor.apply();
                            break;
                        case "关闭SIM检测":
                            editor.putBoolean("detectSIM", false);
                            editor.apply();
                            break;
                        case "销毁数据":
                            if (sp.getBoolean("destroyData", true)) {
                                dpm.wipeData(0);
                            }
                            break;
                        case "报警":
                            if (sp.getBoolean("alarm", true)) {
                                AudioManager audioMa = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                                audioMa.setStreamVolume(2, audioMa.getStreamMaxVolume(2), 1);
                                RingtoneManager.getRingtone(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)).play();
                            }
                            break;
                        case "定位":
                            new Thread(){
                                @Override
                                public void run() {
                                    gpsUtil.getPos(location -> {
                                        String mobile = sp.getString("securityMobile", "NULL");
                                        if (!mobile.equals("NULL")){
                                            SMS sms=new SMS();
                                            sms.send("经度:"+location.getLongitude() +"纬度"+location.getLatitude(),mobile);
                                        }
                                    });
                                }
                            }.start();
                            break;
                    }
                    break;
                }
                break;
            }
            futhertime=SystemClock.elapsedRealtime()+3000;
        }else{
            Log.i("emmm 时间未到","指令无效");
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        registerSimReceiver(false);
        Log.i("emmm","服务被关闭");
    }
    public void registerSimReceiver(boolean register) {
        if (register) {
            if (simStateReceiver == null) {
                simStateReceiver = new SimStateReceiver();
                simStateReceiver.setOnSimSwitchListener(valid -> {
                    if (!valid) {
                        Log.i("emmmmmm手机卡被拔了","锁屏");
                        if (sp.getBoolean("detectSIM",true)){
                            dpm.lockNow();
                        }
                    }else {
                        Log.i("emmmmmm","手机卡回来了");
                    }
                });
            }
            IntentFilter intentFilter = new IntentFilter(SimStateReceiver.ACTION_SIM_STATE_CHANGED);
            if (!hasRegister)
                hasRegister = true;
                this.registerReceiver(simStateReceiver, intentFilter);
        } else {
            if (simStateReceiver != null && hasRegister) {
                hasRegister = false;
                this.unregisterReceiver(simStateReceiver);
            }
        }
    }
}